package com.cloudinnov.utils;

import com.cloudinnov.utils.support.spring.SpringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class LightDetectorClient {
	private static final Logger LOG = LoggerFactory.getLogger(LightDetectorClient.class);
	public static final String TOTAL_CAR = "total:light";
	public static final String CAL_NAME = "light:deviceId:";
	public static final String CAL_VALUE = ":value";
	private static final int RECENT_LIST_COUNT = 10000;
	public static final String SPLITTER_LEVEL0 = ",";
	private  String serverIP;
	private int port;
	private Socket socket;
	private boolean isRunning = true;
	private OutputStream out;
	private String equipCode;
	static JedisPool jedisPool = (JedisPool) SpringUtils.getBean("jedisPool");

	public LightDetectorClient(String receiveIp, int port, String equipCode) {
		this.serverIP = receiveIp;
		this.port = port;
		this.equipCode = equipCode;
	}

	public static void main(String[] args) throws IOException {
		List<String> list = new ArrayList();
		list.add("127.0.0.1");
		list.add("10.168.2.210");
		for (int i = 0; i < list.size(); i++) {
			LightDetectorClient client = new LightDetectorClient((String) list.get(i), 4196, i + "ice");
			client.start();
		}
	}

	public void start() {
		try {
			this.socket = new Socket(serverIP, this.port);
			 
			new Thread(new ReceiveMsgInfo()).start();
		} catch (IOException e) {
			LOG.error("建立连接成功");
		}
	}

	public void sendObject(byte[] datas) throws IOException {
		this.out.write(datas);
		this.out.flush();
	}

	class SendMsgInfo implements Runnable {
		SendMsgInfo() {
		}

		public void run() {
			while (LightDetectorClient.this.isRunning) {
				try {
					LightDetectorClient.this.sendObject(LightDetectorClient.cqewSendData());
					Thread.sleep(5000L);
				} catch (IOException | InterruptedException e) {
					LightDetectorClient.this.isRunning = false;
					LightDetectorClient.LOG.error("TCP Client Error");
				}
			}
		}
	}

	class ReceiveMsgInfo implements Runnable {
		private int totalBytesRcvd;

		ReceiveMsgInfo() {
		}

		public void run() {
			Jedis redis = null;
			redis = LightDetectorClient.jedisPool.getResource();

			byte[] tmp = new byte[1024];
			while (LightDetectorClient.this.isRunning) {
				try {
					InputStream in = LightDetectorClient.this.socket.getInputStream();
					this.totalBytesRcvd = 0;
					int bytesRcvd;
					if ((bytesRcvd = in.read(tmp, this.totalBytesRcvd, tmp.length - this.totalBytesRcvd)) == -1) {
						throw new SocketException("Connection closed prematurely");
					}
					this.totalBytesRcvd += bytesRcvd;
					byte[] copyOf = Arrays.copyOf(tmp, this.totalBytesRcvd);
					LightDetectorClient.parseData(copyOf, redis, LightDetectorClient.this.equipCode);
				} catch (Exception localException) {
				}
			}
		}
	}

	public static byte[] cqewSendData() {
		byte[] send = new byte[16];
		send[0] = ((byte) hex2Low(1));
		send[1] = ((byte) hex2Low(16));
		send[2] = ((byte) hex2Low(1));
		send[3] = ((byte) hex2Low(48));
		send[4] = ((byte) hex2Low(22));
		send[5] = ((byte) hex2Low(240));
		send[6] = ((byte) hex2Low(4));
		send[7] = ((byte) hex2Low(2));
		send[8] = ((byte) hex2Low(35));
		send[9] = ((byte) hex2Low(16));
		send[10] = ((byte) hex2Low(89));
		send[11] = ((byte) hex2Low(2));
		send[12] = ((byte) hex2Low(3));
		send[13] = ((byte) hex2Low(13));
		send[14] = ((byte) hex2Low(212));
		send[15] = ((byte) hex2Low(4));
		return send;
	}

	public static void parseData(byte[] result, Jedis redis, String equipCode) {
		if ((result[0] == 1) && (result[(result.length - 1)] == 4) && (result[7] == 2) && (result[10] == 0)) {
			List<String> list = new ArrayList();
			String tmpString = "";
			Integer length = Integer.valueOf(hex2Low(result[6]) - 6);
			for (int i = 14; i < length.intValue() + 14; i++) {
				int tmp = result[i];
				if (tmp == 0) {
					tmpString = "00";
				}
				if (tmp < 0) {
					int hex2Low = hex2Low(result[i]);

					tmpString = Integer.toHexString(hex2Low);
				}
				if (tmp > 15) {
					int hex2Low = hex2Low(result[i]);
					tmpString = Integer.toHexString(hex2Low);
				}
				if ((tmp <= 15) && (tmp > 0)) {
					int hex2Low = hex2Low(result[i]);
					tmpString = "0" + Integer.toHexString(hex2Low);
				}
				list.add(tmpString);
			}
			Collections.reverse(list);
			String dataResult = "";
			for (int j = 0; j < list.size(); j++) {
				dataResult = dataResult + (String) list.get(j);
			}
			float intBitsToFloat = Float.intBitsToFloat(Integer.parseInt(dataResult, 16));
			LOG.info("能见度检测器:" + equipCode + ":" + intBitsToFloat);
			String keyRealtime = "light:deviceId:" + equipCode + ":value";
			String totalName = "total:light:value";
			String value = intBitsToFloat + "," + System.currentTimeMillis();
			redis.lpush(keyRealtime, new String[] { value });
			redis.ltrim(keyRealtime, 0L, 10000L);
			redis.set(totalName, value);
			jedisPool.returnResource(redis);
		}
	}

	public static int hex2Low(int num) {
		byte a = (byte) num;
		int i = a;
		i = a & 0xFF;
		return i;
	}
}
